import { useState, useRef, useEffect } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import styles from './index.module.css'
import img from '../wenz/img/image.png'
import Nabar from '../../conpoment/Nabar'
import { AddOutline } from 'antd-mobile-icons'
import img1 from '../wenz/img/tij1.png'
import img2 from '../wenz/img/tji2.png'
import img3 from '../wenz/img/tji3.png'
import { uploadFile, UploadProgress, UploadResult } from '../../utils/simpleOssUpload'
interface Message {
  id: string
  type: 'user' | 'assistant'
  content: string
  timestamp: Date
  images?: string[] // 添加图片URL数组
}
interface SavedProfile {
  name: string
  standing: string
  birthday: string
  sex: string
  phone: string
  relation: string
  age: string
}       
function Index() {
  const navigate = useNavigate()
  const location = useLocation()
  const [inputText, setInputText] = useState('')
  const [savedProfile, setSavedProfile] = useState<SavedProfile | null>(null)
  const [messages, setMessages] = useState<Message[]>([
    {
      id: '1',
      type: 'assistant',
      content: '您好,我是您的医生助手。',
      timestamp: new Date()
    },
    {
      id: '2',
      type: 'assistant',
      content: '请在下方输入框详细描述病情,以便医生准确了解您的情况,快速接诊',
      timestamp: new Date()
    }
  ])
  const [isLoading, setIsLoading] = useState(false)
  const [showImageUpload, setShowImageUpload] = useState(false)
  const [uploadedImages, setUploadedImages] = useState<File[]>([])
  const [imagePreviewUrls, setImagePreviewUrls] = useState<string[]>([])
  const [uploadResults, setUploadResults] = useState<UploadResult[]>([])
  const [uploadProgress, setUploadProgress] = useState<{ [key: number]: UploadProgress }>({})
  const [isUploading, setIsUploading] = useState(false)
  const [previewImage, setPreviewImage] = useState<string | null>(null)
  const [showLoginButton, setShowLoginButton] = useState(false)
  const [showNextStepButton, setShowNextStepButton] = useState(false)
  const [showProfileSelection, setShowProfileSelection] = useState(false)
  const [currentStep, setCurrentStep] = useState(1) // 当前步骤：1-描述病情，2-匹配医生，3-开始咨询
  const [showProgressBar] = useState(true) // 控制进度条显示/隐藏
  const [profileSelected, setProfileSelected] = useState(false) // 控制档案是否已选择
  const messagesEndRef = useRef<HTMLDivElement>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)
  // 自动滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }
  useEffect(() => {
    scrollToBottom()
  }, [messages])
  // 检查登录状态
  const checkLoginStatus = () => {
    const token = localStorage.getItem('token')
    return !!token
  }
  // 页面加载时检查登录状态
  useEffect(() => {
    checkLoginStatus()
  }, [])
  // 接收从创建档案页面传递的数据
  useEffect(() => {
    if (location.state && location.state.fromCreate) {
      setSavedProfile(location.state.savedProfile)
      setShowProfileSelection(true) // 直接显示选择档案界面
      console.log('接收到保存的档案数据:', location.state.savedProfile)
    }
    
    // 通过sessionStorage判断上一个路由
    const lastRoute = sessionStorage.getItem('lastRoute')
    if (lastRoute === '/create') {
      setShowProfileSelection(true)
      console.log('检测到从create页面跳转')
      // 清理sessionStorage，避免重复触发
      sessionStorage.removeItem('lastRoute')
    }
  }, [location.state])
  // 跳转到登录页面
  const handleLoginClick = () => {
    navigate('/login')
  }
  // 医生助手回复逻辑
  const getAssistantReply = (): string => {
    const replies = [
      '感谢您详细的描述，我已经了解了您的情况。请上传能反应患者病情的相关资料,上传的资料仅自己和医生可见。',
      '根据您的描述，我建议您注意休息，多喝水。请上传能反应患者病情的相关资料,上传的资料仅自己和医生可见。',
      '您的症状我已经记录，正在为您匹配合适的医生。请上传能反应患者病情的相关资料,上传的资料仅自己和医生可见。',
      '请保持耐心，我们的专业医生会尽快为您提供帮助。请上传能反应患者病情的相关资料,上传的资料仅自己和医生可见。',
      '您的病情描述很详细，这对医生诊断很有帮助。请上传能反应患者病情的相关资料,上传的资料仅自己和医生可见。',
      '我已经收到您的信息，正在安排医生为您服务。请上传能反应患者病情的相关资料,上传的资料仅自己和医生可见。'
    ]
    return replies[Math.floor(Math.random() * replies.length)]
  }
  const handleSubmit = async () => {
    if (inputText.length < 5) {
      alert('请输入至少5个字符描述病情')
      return
    }
    if (inputText.length > 500) {
      alert('描述内容不能超过500个字符')
      return
    }
    // 添加用户消息
    const userMessage: Message = {
      id: Date.now().toString(),
      type: 'user',
      content: inputText,
      timestamp: new Date()
    }
    setMessages(prev => [...prev, userMessage])
    setInputText('')
    setIsLoading(true)
    // 模拟医生助手回复延迟
    setTimeout(() => {
      const assistantReply: Message = {
        id: (Date.now() + 1).toString(),
        type: 'assistant',
        content: getAssistantReply(),
        timestamp: new Date()
      }
      setMessages(prev => [...prev, assistantReply])
      setIsLoading(false)
      // 显示图片上传界面
      setShowImageUpload(true)
      // 更新进度到第二步
      setCurrentStep(2)
    }, 1500)
  }
  const handleAgreementClick = () => {
    // 这里可以打开风险告知同意书页面
    console.log('打开风险告知及患者知情同意书')
  }
  // 图片上传处理
  const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files
    if (files) {
      const newFiles = Array.from(files).slice(0, 9 - uploadedImages.length)
      const newUrls = newFiles.map(file => URL.createObjectURL(file))
      setUploadedImages(prev => [...prev, ...newFiles])
      setImagePreviewUrls(prev => [...prev, ...newUrls])
      // 自动开始上传
      startUpload(newFiles)
    }
  }
  // 开始上传文件到OSS
  const startUpload = async (files: File[]) => {
    setIsUploading(true)
    for (let i = 0; i < files.length; i++) {
      const file = files[i]
      const fileIndex = uploadedImages.length + i
      try {
        await uploadFile(file, {
          onProgress: (progress) => {
            setUploadProgress(prev => ({
              ...prev,
              [fileIndex]: progress
            }))
          },
          onSuccess: (result) => {
            setUploadResults(prev => [...prev, result])
            console.log('文件上传成功:', result)
          },
          onError: (error) => {
            console.error('文件上传失败:', error)
            alert(`文件 ${file.name} 上传失败: ${error.message}`)
          }
        })
      } catch (error) {
        console.error('上传过程中发生错误:', error)
      }
    }
    setIsUploading(false)
  }
  // 删除图片
  const removeImage = (index: number) => {
    setUploadedImages(prev => prev.filter((_, i) => i !== index))
    setImagePreviewUrls(prev => {
      URL.revokeObjectURL(prev[index])
      return prev.filter((_, i) => i !== index)
    })
    setUploadResults(prev => prev.filter((_, i) => i !== index))
    setUploadProgress(prev => {
      const newProgress = { ...prev }
      delete newProgress[index]
      return newProgress
    })
  }
  // 跳过图片上传
  const handleSkip = () => {
    // 检查登录状态
    if (!checkLoginStatus()) {
      setShowLoginButton(true)
      setShowImageUpload(false)
      return
    }
    // 添加跳过消息到聊天记录
    const skipMessage: Message = {
      id: Date.now().toString(),
      type: 'user',
      content: '',
      timestamp: new Date(),
      images: ['no-image'] // 使用特殊标识表示跳过
    }
    setMessages(prev => [...prev, skipMessage])
    // 模拟医生助手回复
    setTimeout(() => {
      const assistantReply: Message = {
        id: (Date.now() + 1).toString(),
        type: 'assistant',
        content: '请问您想为一下哪位患者咨询',
        timestamp: new Date()
      }
      setMessages(prev => [...prev, assistantReply])
      // 显示下一步按钮
      setShowNextStepButton(true)
      // 更新进度到第三步
      setCurrentStep(3)
    }, 1000)
    setShowImageUpload(false)
    // 清理上传状态
    setUploadedImages([])
    setImagePreviewUrls([])
    setUploadResults([])
    setUploadProgress({})
    console.log('跳过图片上传')
  }
  // 确认图片上传
  const handleConfirm = () => {
    if (isUploading) {
      alert('文件正在上传中，请稍候...')
      return
    }
    // 检查登录状态
    if (!checkLoginStatus()) {
      setShowLoginButton(true)
      setShowImageUpload(false)
      return
    }
    // 将上传的图片添加到聊天记录
    if (uploadResults.length > 0) {
      const imageUrls = uploadResults.map(result => result.url)
      const imageMessage: Message = {
        id: Date.now().toString(),
        type: 'user',
        content: '',
        timestamp: new Date(),
        images: imageUrls
      }
      setMessages(prev => [...prev, imageMessage])
      // 模拟医生助手回复
      setTimeout(() => {
        const assistantReply: Message = {
          id: (Date.now() + 1).toString(),
          type: 'assistant',
          content: '请问你想为一下哪位患者咨询',
          timestamp: new Date()
        }
        setMessages(prev => [...prev, assistantReply])
        // 显示下一步按钮
        setShowNextStepButton(true)
        // 更新进度到第三步
        setCurrentStep(3)
      }, 1000)
    }
    setShowImageUpload(false)
    // 清理上传状态
    setUploadedImages([])
    setImagePreviewUrls([])
    setUploadResults([])
    setUploadProgress({})
    console.log('确认上传的图片:', uploadedImages)
    console.log('上传结果:', uploadResults)
  }
  return (
    <div className={styles.container}>
      {/* 顶部导航栏 */}
      <div className={styles.header}>
        <Nabar title='描述病情' sticky={false} />
      </div>
      {/* 进度指示器 */}
      {showProgressBar && (
        <div className={styles.progressContainer}>
          <div className={styles.progressSteps}>
            <div className={`${styles.stepItem} ${currentStep >= 1 ? styles.active : ''}`}>
              <div className={styles.stepText}>描述病情</div>
            </div>
            <div className={styles.stepArrow}>→</div>
            <div className={`${styles.stepItem} ${currentStep >= 2 ? styles.active : ''}`}>
              <div className={styles.stepText}>匹配医生</div>
            </div>
            <div className={styles.stepArrow}>→</div>
            <div className={`${styles.stepItem} ${currentStep >= 3 ? styles.active : ''}`}>
              <div className={styles.stepText}>开始咨询</div>
            </div>
          </div>
        </div>
      )}
      {/* 服务保障 */}
      <div className={styles.serviceGuarantee}>
        <div className={styles.guaranteeTitle}>
          <span className={styles.shieldIcon}>🛡️</span>
          服务保障
        </div>
        <div className={styles.guaranteeItems}>
          <div className={styles.guaranteeItem}>专业医生</div>
          <div className={styles.guaranteeItem}>实名认证</div>
          <div className={styles.guaranteeItem}>多轮沟通</div>
          <div className={styles.guaranteeItem}>超时退款</div>
        </div>
      </div>
      {/* 风险告知 */}
      <div className={styles.agreementContainer}>
        <div className={styles.agreementText}>
          请您仔细阅读
          <span
            className={styles.agreementLink}
            onClick={handleAgreementClick}
          >
            《风险告知及患者知情同意书》
          </span>
          ,如非复诊,我们仅提供医疗咨询服务。继续操作表示您知悉并同意上述告知内容。
        </div>
      </div>

      {/* 医生助手对话 */}
      <div className={styles.chatContainer}>
        {messages.map((message) => (
          <div
            key={message.id}
            className={`${styles.chatMessage} ${message.type === 'user' ? styles.userMessage : ''}`}
          >
            <div className={styles.avatar}>
              <img src={img} alt="医生助手" />
            </div>
            <div className={`${styles.messageBubble} ${message.type === 'user' ? styles.userBubble : ''}`}>
              {message.content}
              {/* 显示图片或暂无图片 */}
              {message.images && message.images.length > 0 && (
                <div className={styles.messageImages}>
                  {message.images.map((imageUrl, index) => {
                    // 如果是跳过标识，显示"暂无图片"
                    if (imageUrl === 'no-image') {
                      return (
                        <div className={styles.noImageText}>暂无图片</div>
                      )
                    }
                    // 正常显示图片
                    return (
                      <div key={index} className={styles.messageImageContainer}>
                        <img
                          src={imageUrl}
                          alt=''
                          className={styles.messageImage}
                          onClick={() => {
                            // 点击图片显示预览
                            setPreviewImage(imageUrl)
                          }}
                        />
                      </div>
                    )
                  })}
                </div>
              )}
            </div>
          </div>
        ))}
        {isLoading && (
          <div className={styles.chatMessage}>
            <div className={styles.avatar}>
              <img src={img} alt="医生助手" />
            </div>
            <div className={styles.messageBubble}>
              <div className={styles.typingIndicator}>
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        )}
        <div ref={messagesEndRef} />
      </div>
      {/* 底部区域 - 根据状态显示不同界面 */}
      {showLoginButton ? (
        /* 登录提示界面 */
        <div className={styles.loginContainer}>
          <button
            className={styles.loginButton}
            onClick={handleLoginClick}
          >
            立即登录
          </button>
          <p style={{ fontSize: '15px', textAlign: 'center', color: '#666', marginTop: '10px' }}>您需要登录后才能继续使用问诊服务</p>
        </div>
      ) : profileSelected ? (
        /* 档案已选择确认界面 */
            <div className={styles.selectedContainers}>
              <div className={styles.selectedText}>
                <p>根据您的描述</p>
                <p>为您分诊到 <span style={{color:'#f38e12'}}>【全科】</span> <span style={{float:'right'}}>重选科室</span></p>
              </div>
              <div className={styles.selectedText}>
                <p><span style={{fontWeight:'600',fontSize:'16px',marginRight:'5px'}}>
                  为您推荐</span><span>智能匹配医生·未接诊可退款</span>
                  </p>
              </div>
              <div style={{marginRight:'5px'}}>
                <div style={{display:'flex',alignItems:'center',gap:'5px'
                  ,marginTop:'10px'}} onClick={()=>navigate(`/price/${6.90}`)}>
                  <span><img src={img1} alt="" /></span>
                  <span style={{flex:1}}>
                    <p>极速图文问诊 <span style={{color:'#f38e12',border:'1px solid #f38e12'
                      ,borderRadius:'20px',padding:'2px 5px'}}>推荐</span>
                      <span style={{float:'right'}}>
                        <span className={styles.strikethrough_price}>￥9.9</span>
                        <span style={{color:'#f38e12',fontWeight:'600',fontSize:'14px'}}
                        >￥6.90</span>
                      </span>
                    </p>
                    <p>平均3分钟接诊，交流时长，30条消息/30分钟</p>
                  </span>
                </div>
                <div style={{display:'flex',gap:'10px',marginTop:'10px'}} 
                 onClick={()=>navigate(`/price/${30.00}`)}>
                  <span><img src={img2} alt="" style={{marginLeft:'-2px'}}/></span>
                  <span style={{flex:1}}>
                    <p>极速图文问诊 <span style={{color:'#f38e12',border:'1px solid #f38e12'
                      ,borderRadius:'20px',padding:'2px 5px'}}>推荐</span>
                      <span style={{float:'right'}}>
                        <span className={styles.strikethrough_price}>￥59.9</span>
                        <span style={{color:'#f38e12',fontWeight:'600',fontSize:'14px'}}>
                          ￥30.00</span>
                      </span>
                    </p>
                    <p>平均3分钟接诊，交流时长，30条消息/30分钟</p>
                  </span>
                </div>
                <div style={{display:'flex',alignItems:'center',gap:'5px',marginTop:'10px' }}
                  onClick={()=>navigate(`/price/${50.00}`)}>
                  <span><img src={img3} alt="" /></span>
                  <span style={{flex:1}}>
                    <p>极速图文问诊 <span style={{color:'#f38e12',border:'1px solid #f38e12'
                      ,borderRadius:'20px',padding:'2px 5px'}}>推荐</span>
                      <span style={{float:'right'}}>
                        <span className={styles.strikethrough_price}>￥99.9</span>
                        <span style={{color:'#f38e12',fontWeight:'600',fontSize:'14px'}}
                        >￥50.00</span>
                      </span>
                    </p>
                    <p>平均3分钟接诊，交流时长，30条消息/30分钟</p>
                  </span>
                </div>
              </div>
            </div>
   
      ) : showProfileSelection ? (
        /* 选择档案界面 - 从create页面跳转时直接显示 */
        <div>
          <div className={styles.nextStepContainer}>
            <div className={styles.profileSection}>
              <b>选择档案</b>
              <span
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '5px',
                  color: '#1890ff',
                  cursor: 'pointer',
                  marginLeft: '230px'
                }}
                onClick={() => navigate('/create')}
              >
                <AddOutline />添加档案
              </span>
            </div>
          </div>
          <div className={styles.xx}>
            {/* 显示已保存的档案信息 */}
            {savedProfile && (
              <div className={styles.savedProfile}>
                <div className={styles.profileCard}>
                  <div className={styles.profileHeader}>
                    <span className={styles.profileName}>{savedProfile.name}</span>
                    <span className={styles.profileRelation}>({savedProfile.relation})</span>
                  </div>
                  <div className={styles.profileDetails}>
                    <span className={styles.profileAge}>{savedProfile.age}</span>
                    <span className={styles.profileGender}>{savedProfile.sex}</span>
                    <span className={styles.profilePhone}>
                      {savedProfile.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')}
                    </span>
                  </div>
                  <div className={styles.profileIdCard}>
                    {savedProfile.standing.replace(/(\d{6})\d{8}(\d{4})/, '$1********$2')}
                  </div>
                </div>
                <div className={styles.profileActions}>
                  <button
                    className={styles.selectButton}
                    onClick={() => {
                      console.log('选择档案:', savedProfile)
                      // 更新进度到匹配医生步骤
                      setCurrentStep(2)
                      // 标记档案已选择
                      setProfileSelected(true)
                      // 隐藏选择档案的盒子
                      setShowProfileSelection(false)
                      // 这里可以添加选择档案后的逻辑
                    }}
                  >
                    选择此档案
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
      ) : showNextStepButton ? (
        /* 下一步按钮界面 */
        <div>
          <div className={styles.nextStepContainer}>
            <div className={styles.profileSection}>
              <b>选择档案</b>
              <span
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '5px',
                  color: '#1890ff',
                  cursor: 'pointer',
                  marginLeft: '230px'
                }}
                onClick={() => navigate('/create')}
              >
                <AddOutline />添加档案
              </span>
            </div>
          </div>
          <div className={styles.xx}>
            {/* 显示已保存的档案信息 */}
            {savedProfile && (
              <div className={styles.savedProfile}>
                <div className={styles.profileCard}>
                  <div className={styles.profileHeader}>
                    <span className={styles.profileName}>{savedProfile.name}</span>
                    <span className={styles.profileRelation}>({savedProfile.relation})</span>
                  </div>
                  <div className={styles.profileDetails}>
                    <span className={styles.profileAge}>{savedProfile.age}</span>
                    <span className={styles.profileGender}>{savedProfile.sex}</span>
                    <span className={styles.profilePhone}>
                      {savedProfile.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')}
                    </span>
                  </div>
                  <div className={styles.profileIdCard}>
                    {savedProfile.standing.replace(/(\d{6})\d{8}(\d{4})/, '$1********$2')}
                  </div>
                </div>
                <div className={styles.profileActions}>
                  <button
                    className={styles.selectButton}
                    onClick={() => {
                      console.log('选择档案:', savedProfile)
                      // 这里可以添加选择档案后的逻辑
                    }}
                  >
                    选择此档案
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>

      ) : showImageUpload ? (
        /* 图片上传界面 */
        <div className={styles.imageUploadContainer}>
          <div className={styles.uploadHeader}>
            <h3 className={styles.uploadTitle}>上传图片 (选填)</h3>
            <button className={styles.skipButton} onClick={handleSkip}>
              跳过
            </button>
          </div>
          <p className={styles.uploadSubtitle}>
            检查单/历史病例/患处照片 (最多9张)
          </p>
          <div className={styles.imageGrid}>
            {imagePreviewUrls.map((url, index) => {
              const progress = uploadProgress[index]
              const isUploaded = uploadResults[index]
              return (
                <div key={index} className={styles.imagePreview}>
                  <img src={url} alt={`预览 ${index + 1}`} />
                  {/* 上传进度覆盖层 */}
                  {progress && !isUploaded && (
                    <div className={styles.uploadOverlay}>
                      <div className={styles.progressBar}>
                        <div
                          className={styles.progressFill}
                          style={{ width: `${progress.percent}%` }}
                        ></div>
                      </div>
                      <div className={styles.progressText}>
                        {progress.percent}%
                      </div>
                    </div>
                  )}
                  {/* 上传成功标识 */}
                  {isUploaded && (
                    <div className={styles.uploadSuccess}>
                      <div className={styles.successIcon}>✓</div>
                    </div>
                  )}
                  <button
                    className={styles.removeButton}
                    onClick={() => removeImage(index)}
                    disabled={isUploading}
                  >
                  </button>
                </div>
              )
            })}
            {uploadedImages.length < 9 && (
              <div
                className={styles.uploadArea}
                onClick={() => fileInputRef.current?.click()}
              >
                <div className={styles.uploadIcon}>+</div>
                <p className={styles.uploadText}>点击上传</p>
              </div>
            )}
          </div>
          <input
            ref={fileInputRef}
            type="file"
            accept="image/*"
            multiple
            onChange={handleImageUpload}
            style={{ display: 'none' }}
          />
          <button
            className={styles.confirmButton}
            onClick={handleConfirm}
            disabled={isUploading}
          >
            {isUploading ? '上传中...' : '确定'}
          </button>
        </div>
      ) : (
        /* 文本输入界面 */
        <div className={styles.inputContainer}>
          <div className={styles.inputWrapper}>
            <textarea
              className={styles.textInput}
              placeholder="请用5-500字描述具体症状、患病时长、用药情况、需要医生提供哪些帮助等, 以便医生更好帮助您解决问题。"
              value={inputText}
              onChange={(e) => setInputText(e.target.value)}
              maxLength={500}
            />
            <div className={styles.charCount}>
              {inputText.length}/500
            </div>
          </div>
          <button
            className={styles.submitButton}
            onClick={handleSubmit}
            disabled={isLoading}
          >
            {isLoading ? '发送中...' : '发送'}
          </button>
        </div>
      )}
      {/* 图片预览模态框 */}
      {previewImage && (
        <div className={styles.imagePreviewModal} onClick={() => setPreviewImage(null)}>
          <div className={styles.imagePreviewContent} onClick={(e) => e.stopPropagation()}>
            <button
              className={styles.closeButton}
              onClick={() => setPreviewImage(null)}
            >
              ×
            </button>
            <img
              src={previewImage}
              alt="预览图片"
              className={styles.previewImage}
            />
          </div>
        </div>
      )}
    </div>
  )
}
export default Index